<template>
  <div>
    <el-button-group>
      <el-button type="primary" @click.native="handleForm('add', null)">新增</el-button>
    </el-button-group>
    <el-table v-loading="loading" :data="list">
      <el-table-column prop="id" label="用户ID" />
      <el-table-column :show-overflow-tooltip="true" prop="name" label="角色名称" />
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilterType">{{
            scope.row.status | statusFilterName
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="描述" />
      <el-table-column label="操作" width="240px">
        <template slot-scope="scope">
          <el-button :loading="authBtnLoading" type="success" size="small" @click.native="handleAuth(scope.row.id)">授权
          </el-button>
          <el-button slot="reference" size="mini" type="primary" @click.native="handleForm('edit', scope.row)">编辑
          </el-button>
          <el-button
            slot="reference"
            :loading="deleteLoading"
            size="mini"
            type="danger"
            @click.native="handleDel(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      :current-page="listInfo.current_page"
      :total="listInfo.total"
      :page-size="listInfo.per_page"
      layout="total, sizes, prev, pager, next, jumper"
      background
      @size-change="size => GetList(1, size)"
      @current-change="(page, size) => GetList(page)" />

    <!--授权界面-->
    <el-dialog :visible.sync="authFormVisible" :close-on-click-modal="false" title="授权" class="dialog" top="5vh" >
      <el-tree
        ref="tree"
        :data="authList"
        :props="defaultProps"
        :default-checked-keys="authDefaultCheckedKeys"
        style="max-height: 60vh;overflow-y: auto;"
        show-checkbox=""
        default-expand-all=""
        node-key="id" />
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="authFormVisible = !authFormVisible">取消</el-button>
        <el-button :loading="authLoading" type="primary" @click.native="authSubmit()">提交
        </el-button>
      </div>
    </el-dialog>

    <!--表单-->
    <el-dialog :title="formMap[formName]" :visible.sync="formVisible" :before-close="hideForm" width="85%" top="5vh">
      <el-form ref="dataForm" :rules="formRules" :model="formData">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" auto-complete="off" />
        </el-form-item>
        <el-form-item label="排序" prop="listorder">
          <el-input v-model="formData.listorder" type="" auto-complete="off" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="formData.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="hideForm">取消</el-button>
        <el-button :loading="formLoading" type="primary" @click.native="formSubmit()">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const formJson = {
  name: '',
  listorder: 999,
  remark: '',
  status: 1
}
export default {
  name: 'PermissionRole',
  filters: {
    statusFilterType(status) {
      const statusMap = {
        1: 'success',
        2: 'gray'
      }
      return statusMap[status]
    },
    statusFilterName(status) {
      const statusMap = {
        1: '正常',
        2: '禁用'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      where: {},
      listInfo: {},
      list: [],
      loading: false,
      formVisible: false,
      formData: formJson,
      deleteLoading: false,
      formLoading: false,
      formName: null,
      formMap: {
        add: '新增',
        edit: '编辑'
      },
      formRules: {
        name: [{
          required: true,
          message: '请输入角色名称',
          trigger: 'blur'
        }],
        listorder: [{
          required: true,
          message: '请输入排序',
          trigger: 'blur'
        }],
        remark: [{
          required: true,
          message: '请输入描述',
          trigger: 'blur'
        }]
      },
      // 权限
      authList: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      authLoading: false,
      authBtnLoading: false,
      authFormVisible: false,
      authFormData: {
        role_id: '',
        auth_rules: []
      },
      authDefaultCheckedKeys: []
    }
  },
  mounted() {
    this.GetList()
  },
  methods: {
    // 显示授权界面
    handleAuth(roleId) {
      this.authFormData.role_id = roleId
      this.authFormData.auth_rules = []
      this.authList = []
      this.authBtnLoading = true
      this.$http.get(`permissionRule/auth-list/${roleId}`).then(response => {
        this.authFormVisible = true
        this.authBtnLoading = false
        this.authList = response.resource.auth_list || []
        const checkedKeys = response.resource.checked_keys || []
        const tempCheckedKeys = []
        let id = null
        let node = null
        const getTreeNode = function(arr, id) {
          for (const i in arr) {
            const tempNode = arr[i]
            if (tempNode.id === id) {
              // 找到了，就不找了
              node = tempNode
            }
            // 如果还有子节点，再继续找
            getTreeNode(tempNode.children, id)
          }
        }
        for (const i in checkedKeys) {
          id = checkedKeys[i]
          getTreeNode(this.authList, id)
          if (node && node.children.length <= 0) {
            // 如果下面没有子节点，则加入
            tempCheckedKeys.push(id)
          }
        }
        this.authDefaultCheckedKeys = []
        this.authDefaultCheckedKeys = tempCheckedKeys
        // this.$refs.tree.setCheckedKeys(tempCheckedKeys);
      }).catch(() => {
        this.authFormVisible = false
        this.authBtnLoading = false
      })
    },
    authSubmit() {
      this.authLoading = true
      const getNodeParents = function(node) {
        let arr = []
        const id = node.data.id || null
        if (id) {
          arr.push(node.data.id)
        }
        if (node.parent) {
          arr = arr.concat(getNodeParents(node.parent))
        }
        return arr
      }
      const checkedKeys = this.$refs.tree.getCheckedKeys()
      let arr = []
      for (const checkedKey of checkedKeys) {
        const node = this.$refs.tree.getNode(checkedKey)
        arr = arr.concat(getNodeParents(node))
      }
      const setArr = new Set(arr)
      this.authFormData.auth_rules = [...setArr]
      if (!this.authFormData) {
        this.$alert('请至少选择一个权限', '提示', {
          confirmButtonText: '确定'
        })
        return false
      }
      console.log(this.authFormData)
      this.$http.post('permissionRule/auth', this.authFormData).then(response => {
        this.authLoading = false
        this.$message.success('授权成功')
        // 刷新表单
        this.GetList()
        this.authFormVisible = false
      }).catch(() => {
        this.authLoading = false
      })
    },
    // 删除
    handleDel(index, row) {
      if (row.id) {
        this.$confirm('确认删除该记录吗?', () => {
          this.deleteLoading = true
          this.$http.delete(`authRole/role-delete/${row.id}`).then(response => {
            this.deleteLoading = false
            this.$message.success('删除成功')
            // 刷新数据
            this.list.splice(index, 1)
          }).catch(() => {
            this.deleteLoading = false
          })
        }, () => {
          this.$message.info('取消删除')
        })
      }
    },
    // 刷新表单
    resetForm() {
      if (this.$refs['dataForm']) {
        // 清空验证信息表单
        this.$refs['dataForm'].clearValidate()
        // 刷新表单
        this.$refs['dataForm'].resetFields()
      }
    },
    // 表单提交
    formSubmit() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.formLoading = true
          const data = Object.assign({}, this.formData)
          if (this.formName === 'edit') {
            this.$http.post(`authRole/role-edit/${this.formData.id}`, data).then(res => {
              this.formLoading = false
              this.$message.success('修改成功')
              this.GetList()
              this.formVisible = false
              // 刷新表单
              this.resetForm()
            }).catch(err => {
              this.formLoading = false
              this.$message.error(err)
            })
          } else if (this.formName === 'add') {
            this.$http.post('authRole/role-add', data).then(res => {
              this.formLoading = false
              this.$message.success('添加成功')
              this.GetList()
              this.formVisible = false
              // 刷新表单
              this.resetForm()
            }).catch(err => {
              this.formLoading = false
              this.$message.error(err)
            })
          }
        }
      })
    },
    // 显示表单
    handleForm(user, row) {
      this.formVisible = true
      this.formData = JSON.parse(JSON.stringify(formJson))
      if (row !== null) {
        this.formData = Object.assign({}, row)
      }
      this.formName = user
    },
    // 隐藏表单
    hideForm() {
      // 更改值
      this.formVisible = !this.formVisible
      // 清空表单
      this.$refs['dataForm'].resetFields()
      return true
    },
    /**
       *  获取列表
       */
    GetList(page = 1, size) {
      this.loading = true
      size = size || this.listInfo.per_page || 10
      const params = {
        page,
        size,
        ...this.where
      }
      this.$http.get('authRole/role-list', {
        params
      }).then(response => {
        this.listInfo = response.meta
        this.list = response.resource
        this.loading = false
      })
    }
  }
}

</script>
